/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.wryproject.customcomponent;

import com.example.wryproject.utils.ThreadUtil;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.render.Canvas;
import ohos.agp.render.LinearShader;
import ohos.agp.render.Paint;
import ohos.agp.render.Shader;
import ohos.agp.utils.Color;
import ohos.agp.utils.Point;
import ohos.agp.utils.RectFloat;
import ohos.app.Context;

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @since 2021-07-13
 */
public class AudioRateComponent extends Component implements Component.DrawTask, Component.EstimateSizeListener {

    // 中心的X，Y坐标
    private float centerX;
    private float centerY;

    //画笔
    private Paint drawRectPaint;

    //五个柱状图的高度
    private float centerTopOne;
    private float centerTopTwo;
    private float centerTopThree;
    private float centerTopFour;
    private float centerTopFive;
    private Timer timer;

    public AudioRateComponent(Context context) {
        this(context, null, null);
    }

    public AudioRateComponent(Context context, AttrSet attrSet) {
        this(context, attrSet, null);
    }

    public AudioRateComponent(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet);
        // 初始化画笔
        // 设置测量组件的侦听器
        setEstimateSizeListener(this);
        initPaint();
        addDrawTask(this);
    }

    /**
     * 初始化画笔
     */
    public void initPaint() {
        //随机画笔颜色
        Random random = new Random();
        List<String> colorList = new ArrayList<>();
        colorList.add("#5F9B30FF");
        colorList.add("#5F00BFFF");
        colorList.add("#5F0000FF");
        colorList.add("#5FEE0000");
        colorList.add("#5FFFA500");
        colorList.add("#5F00FF00");
        Color[] colors = new Color[6];
        for (int i = 0; i < colors.length; i++) {
            int colorIndex = random.nextInt(colorList.size());
            colors[i] = new Color(Color.getIntColor(colorList.get(colorIndex)));
        }
        this.drawRectPaint = new Paint();
        Point pointOne = new Point(centerX, centerY);
        Point pointTwo = new Point(centerX, centerY - 100);
        Point[] point = {pointOne, pointTwo};

        //线性渲染器实现渐变效果
        LinearShader linearShader = new LinearShader(point, null, colors, Shader.TileMode.CLAMP_TILEMODE);
        drawRectPaint.setShader(linearShader, Paint.ShaderType.LINEAR_SHADER);
        drawRectPaint.setStrokeWidth(2);
        drawRectPaint.setStyle(Paint.Style.FILL_STYLE);
    }

    /**
     * 当音乐开始播放时并且此控件显示,就开始刷新
     *
     * @param isPlayer 音乐是否播放
     */
    public void setIsRefresh(boolean isPlayer) {
        if (isPlayer) {
            if (timer == null) {
                timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        if (getVisibility() == Component.VISIBLE) {
                            initPaint();
                            ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
                            int start = 0;
                            int end = 100;

                            //随机数生成柱状图高度
                            centerTopOne = threadLocalRandom.nextInt(start, end);
                            centerTopTwo = threadLocalRandom.nextInt(start, end);
                            centerTopThree = threadLocalRandom.nextInt(start, end);
                            centerTopFour = threadLocalRandom.nextInt(start, end);
                            centerTopFive = threadLocalRandom.nextInt(start, end);

                            //在UI线程中刷新控件
                            ThreadUtil.runUI(() -> invalidate());
                        }
                    }
                }, 0, 200);
            }
        } else {
            if (timer != null) {
                timer.cancel();
                timer = null;
            }
        }
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        drawRect(canvas);
    }

    /**
     * 绘制柱状图
     *
     * @param canvas 画布
     */
    private void drawRect(Canvas canvas) {
        float centerBottom = centerY + 100;
        float centerLeft = centerX - 8;
        float centerRight = centerX + 8;
        float pillarWidth = 16;
        float pillarInterval = 5;

        RectFloat rectOne = new RectFloat();
        rectOne.top = centerTopOne;
        rectOne.bottom = centerBottom;
        rectOne.left = centerLeft - (pillarWidth + pillarInterval) * 2;
        rectOne.right = centerRight - (pillarWidth + pillarInterval) * 2;
        canvas.drawRect(rectOne, drawRectPaint);

        RectFloat rectTwo = new RectFloat();
        rectTwo.top = centerTopTwo;
        rectTwo.bottom = centerBottom;
        rectTwo.left = centerLeft - (pillarWidth + pillarInterval);
        rectTwo.right = centerRight - (pillarWidth + pillarInterval);
        canvas.drawRect(rectTwo, drawRectPaint);

        RectFloat rectThree = new RectFloat();
        rectThree.top = centerTopThree;
        rectThree.bottom = centerBottom;
        rectThree.left = centerLeft;
        rectThree.right = centerRight;
        canvas.drawRect(rectThree, drawRectPaint);

        RectFloat rectFour = new RectFloat();
        rectFour.top = centerTopFour;
        rectFour.bottom = centerBottom;
        rectFour.left = centerLeft + (pillarWidth + pillarInterval);
        rectFour.right = centerRight + (pillarWidth + pillarInterval);
        canvas.drawRect(rectFour, drawRectPaint);

        RectFloat rectFive = new RectFloat();
        rectFive.top = centerTopFive;
        rectFive.bottom = centerBottom;
        rectFive.left = centerLeft + (pillarWidth + pillarInterval) * 2;
        rectFive.right = centerRight + (pillarWidth + pillarInterval) * 2;
        canvas.drawRect(rectFive, drawRectPaint);
    }

    @Override
    public boolean onEstimateSize(int widthEstimateConfig, int heightEstimateConfig) {
        int width = EstimateSpec.getSize(widthEstimateConfig);
        int height = EstimateSpec.getSize(heightEstimateConfig);
        // 宽度和高度
        centerX = (float) width / 2;
        centerY = (float) height / 2;
        setEstimatedSize(
                EstimateSpec.getChildSizeWithMode(width, width, EstimateSpec.NOT_EXCEED),
                EstimateSpec.getChildSizeWithMode(height, height, EstimateSpec.NOT_EXCEED));
        return true;
    }
}
